#!/usr/bin/env python
#coding=utf-8
import httplib
import urllib
import urllib2
import cookielib
import sys
from HTMLParser import HTMLParser

reload(sys)
sys.setdefaultencoding('utf-8')

class AutoRegister(object):
	def __init__(self):
		self.the_page = self.utokenValue = self.values = ''
		self.url = 'http://192.168.21.19/u2.0/Account/Register/sign'
		self.cj = cookielib.CookieJar()
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
		urllib2.install_opener(self.opener)

	def getUntoken(self,response):
		htmlContent = response.read()
		begin = htmlContent.index("<meta name=")
		end = htmlContent.index("</head>") 
		self.utokenValue = htmlContent[begin+29:end-4]
	
	def setInfo(self,username,password,password2,email,inputcode):
		self.values= {'account':username,
		'pwd':password,
		'pwd2':password2,
		'email':email,
		'inputcode':inputcode,
		'invite':'hehe',
		'agree[]':1,
		'utoken':self.utokenValue,
		}
	
	def setCookie(self):
		response = urllib2.urlopen(self.url)
		self.getUntoken(response)

	def register(self,username,password,password2,email,inputcode):	
		self.setCookie()
		self.setInfo(username,password,password2,email,inputcode)
		data = urllib.urlencode(self.values)

		try:
			req = urllib2.Request(self.url, data)
			response = urllib2.urlopen(req)
			self.the_page = response.read()
			if self.the_page.find('注册成功') != -1:
				print "注册成功\n".encode("cp936")
			else:
				print "注册失败\n".encode("cp936")
		except Exception, e:
			print Exception,":",e
			print "注册失败\n".encode("cp936")

	def getPage(self):
		isGetPage = raw_input("是否要打印页面(y/n)\n".encode("cp936"))
		if isGetPage == "y" or isGetPage == "Y":
			print self.the_page.encode("cp936")
		

username = raw_input("请输入用户名\n".encode("cp936"))
password = raw_input("请输入密码\n".encode("cp936"))
password2 = raw_input("请再次输入密码\n".encode("cp936"))
email = raw_input("请输入邮箱\n".encode("cp936"))
inputcode = raw_input("请输入验证码\n".encode("cp936"))


autoRegister = AutoRegister()
autoRegister.register(username,password,password2,email,inputcode)
autoRegister.getPage()
